package com.jw.qme.controller;

import cn.dev33.satoken.util.SaResult;
import com.jw.qme.domain.po.MediaFile;
import com.jw.qme.service.MediaFileService;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/file")
public class FileController {

    private final MediaFileService mediaFileService;

    public FileController(MediaFileService mediaFileService) {
        this.mediaFileService = mediaFileService;
    }

    /**
     * 文件上传接口
     */
    @PostMapping("/upload")
    public SaResult upload(@RequestParam("file") MultipartFile file,
                                   @RequestParam("senderId") String senderId,
                                   @RequestParam("receiverId") String receiverId) throws IOException {
        String fileId = mediaFileService.uploadFile(file, senderId, receiverId);
        return SaResult.data(fileId);
    }

    /**
     * 文件下载接口
     */
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> download(@RequestParam("fileId") String fileId) throws IOException {
        byte[] fileBytes = mediaFileService.downloadFile(fileId);
        MediaFile mediaFile = mediaFileService.getMediaFileById(fileId);

        InputStream inputStream = new ByteArrayInputStream(fileBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(mediaFile.getFileName(), String.valueOf(StandardCharsets.UTF_8)));

        return ResponseEntity.ok()
                .headers(headers)
                .body(new InputStreamResource(inputStream));
    }

}
